package router

import (
	"context"
	"fmt"
	"k8s-dash/config"
	"k8s-dash/utils"
	"log"
	"net/http"
	"os"
	"time"
)

// InitLocalK8sClient 初始化k8sClient
func InitLocalK8sClient() {
	err := utils.K8sClient.Init()
	if err != nil {
		panic(err)
	}
}

// RunServer 优雅启动
func RunServer() {
	r := InitRouter()
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s", config.SysConfig.Default.ListenAddr),
		Handler: r,
	}

	// Initializing the server in a goroutine so that it won't block the graceful shutdown handling below
	go func() {
		log.Println("k8s-dash server started successful on", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Println("start faild", err)
		}
	}()

	// Wait for interrupt signal to gracefully shut down the server with a timeout of 5 seconds.
	quit := utils.SetupSignalHandler()
	<-quit
	log.Println("shutting k8s-dash server down ...")

	// The context is used to inform the server it has 5 seconds to finish the request
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Println("shutting k8s-dash server down ...")
		os.Exit(1)
	}
	log.Println("shutting k8s-dash server down successful")
}
